package com.cysd.ewmxns.sdw_utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
import com.google.zxing.NotFoundException
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import java.io.IOException

object QRCodeDecoder {
    /**
     * 从 Content Uri 解析二维码（优化版）
     * @param context Context
     * @param uri 图片的 content uri
     * @param tryHarder 是否尝试更复杂的识别方式（包括旋转和缩放）
     */
    fun decodeFromContentUri(context: Context, uri: Uri, tryHarder: Boolean = true): String? {
        return try {
            // 获取适当大小的Bitmap（避免内存溢出）
            val bitmap = getOptimizedBitmapFromUri(context, uri) ?: return null

            if (tryHarder) {
                // 增强模式：尝试多种方式识别
                decodeWithMultipleAttempts(bitmap)
            } else {
                // 普通模式：仅尝试原始方向
                decodeFromBitmap(bitmap)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 多尝试策略识别
     */
    private fun decodeWithMultipleAttempts(bitmap: Bitmap): String? {

        try {
            // 尝试1：原始方向
            decodeFromBitmap(bitmap)?.let { return it }

            // 尝试2：常见旋转角度（90, 180, 270）
            val angles = intArrayOf(90, 180, 270, -90, -180, -270)
            for (angle in angles) {
                val rotated = rotateBitmap(bitmap, angle)
                decodeFromBitmap(rotated)?.let { return it }
            }

            // 尝试3：镜像翻转（解决反向扫描问题）
            val mirrored = mirrorBitmap(bitmap)
            decodeFromBitmap(mirrored)?.let { return it }

            // 尝试4：放大图片（有时小图识别困难）
            val scaledUp = scaleBitmap(bitmap, 1.5f)
            decodeFromBitmap(scaledUp)?.let { return it }

            // 尝试5：缩小图片（有时大图包含太多干扰）
            val scaledDown = scaleBitmap(bitmap, 0.7f)
            decodeFromBitmap(scaledDown)?.let { return it }

            return null
        }finally {
            if (!bitmap.isRecycled) {
                bitmap.recycle()
            }
        }

    }

    /**
     * 从 Bitmap 解析条形码/二维码（核心方法优化版）
     */
    private fun decodeFromBitmap(bitmap: Bitmap): String? {
        val width = bitmap.width
        val height = bitmap.height
        val pixels = IntArray(width * height)
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height)

        val source = RGBLuminanceSource(width, height, pixels)
        val binaryBitmap = BinaryBitmap(HybridBinarizer(source))

        return try {
            val hints = mutableMapOf<DecodeHintType, Any>().apply {
                put(DecodeHintType.TRY_HARDER, true)
                put(
                    DecodeHintType.POSSIBLE_FORMATS, listOf(
                        BarcodeFormat.QR_CODE,  // 添加二维码支持
                        BarcodeFormat.EAN_13,
                        BarcodeFormat.EAN_8,
                        BarcodeFormat.UPC_A,
                        BarcodeFormat.UPC_E,
                        BarcodeFormat.CODE_128,
                        BarcodeFormat.CODE_39,
                        BarcodeFormat.ITF
                ))
                put(DecodeHintType.CHARACTER_SET, "UTF-8")
                put(DecodeHintType.PURE_BARCODE, true)  // 假设是纯条形码
            }

            MultiFormatReader().decode(binaryBitmap, hints).text
        } catch (e: NotFoundException) {
            null
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 优化后的图片加载方法（避免OOM）
     */
    private fun getOptimizedBitmapFromUri(context: Context, uri: Uri, maxSize: Int = 1024): Bitmap? {
        return try {
            context.contentResolver.openInputStream(uri)?.use { inputStream ->
                val options = BitmapFactory.Options().apply {
                    inJustDecodeBounds = true
                }
                BitmapFactory.decodeStream(inputStream, null, options)

                // 计算合适的缩放比例
                var scale = 1
                while (options.outWidth / scale > maxSize || options.outHeight / scale > maxSize) {
                    scale *= 2
                }

                val newOptions = BitmapFactory.Options().apply {
                    inSampleSize = scale
                    inPreferredConfig = Bitmap.Config.RGB_565 // 减少内存占用
                }

                context.contentResolver.openInputStream(uri)?.use { newStream ->
                    BitmapFactory.decodeStream(newStream, null, newOptions)
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 旋转 Bitmap（保留原始方法）
     */
    fun rotateBitmap(bitmap: Bitmap, degrees: Int): Bitmap {
        val matrix = Matrix()
        matrix.postRotate(degrees.toFloat())
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    }

    /**
     * 镜像翻转 Bitmap（新增）
     */
    private fun mirrorBitmap(bitmap: Bitmap): Bitmap {
        val matrix = Matrix()
        matrix.preScale(-1f, 1f)
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    }

    /**
     * 缩放 Bitmap（新增）
     */
    private fun scaleBitmap(bitmap: Bitmap, scaleFactor: Float): Bitmap {
        val matrix = Matrix()
        matrix.postScale(scaleFactor, scaleFactor)
        return Bitmap.createBitmap(
            bitmap, 0, 0,
            bitmap.width, bitmap.height,
            matrix, true
        )
    }

    /**
     * 判断图片方向（保留原始方法）
     */
    fun Bitmap.isLandscape(): Boolean {
        return width >= height
    }
}